package xx.iverson.file_manager.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xx.iverson.file_manager.entity.CategoryLevel2;
import xx.iverson.file_manager.mapper.CategoryLevel2Mapper;
import xx.iverson.file_manager.service.CategoryLevel2Service;

import java.util.List;

/**
 * xx.iverson.file_manager.service.impl.CategoryLevel2ServiceImpl
 * 描述：
 * on 2025/9/18-上午9:08
 *
 * @author weijx
 */
@Service
public class CategoryLevel2ServiceImpl implements CategoryLevel2Service {

    @Autowired
    private CategoryLevel2Mapper categoryLevel2Mapper;

    @Override
    public List<CategoryLevel2> getAllLevel2Categories() {
        return categoryLevel2Mapper.selectAllLevel2Categories();
    }

    @Override
    public CategoryLevel2 getLevel2CategoryById(Integer id) {
        return categoryLevel2Mapper.selectLevel2CategoryById(id);
    }

    @Override
    public List<CategoryLevel2> getLevel2CategoriesByLevel1Id(Integer level1Id) {
        return categoryLevel2Mapper.selectLevel2ByLevel1Id(level1Id);
    }

    @Override
    @Transactional
    public boolean addLevel2Category(CategoryLevel2 category) {
        // 检查同一一级分类下二级分类名称是否已存在
        CategoryLevel2 existingCategory = categoryLevel2Mapper.selectLevel2CategoryByNameAndLevel1(
                category.getName(), category.getLevel1Id());
        if (existingCategory != null) {
            return false;
        }

        int result = categoryLevel2Mapper.insertLevel2Category(category);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean updateLevel2Category(CategoryLevel2 category) {
        // 检查同一一级分类下二级分类名称是否已被其他分类使用
        CategoryLevel2 existingCategory = categoryLevel2Mapper.selectLevel2CategoryByNameAndLevel1(
                category.getName(), category.getLevel1Id());
        if (existingCategory != null && !existingCategory.getId().equals(category.getId())) {
            return false;
        }

        int result = categoryLevel2Mapper.updateLevel2Category(category);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteLevel2Category(Integer id) {
        // 检查二级分类是否被文件使用
        if (categoryLevel2Mapper.countFilesByLevel2CategoryId(id) > 0) {
            return false;
        }

        int result = categoryLevel2Mapper.deleteLevel2Category(id);
        return result > 0;
    }

    @Override
    public boolean isLevel2CategoryInUse(Integer categoryId) {
        return categoryLevel2Mapper.countFilesByLevel2CategoryId(categoryId) > 0;
    }

    @Override
    public List<CategoryLevel2> getAllLevel2CategoriesOrderBySort() {
        return categoryLevel2Mapper.selectAllLevel2Categories();
    }
}
